﻿using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using Microsoft.AspNetCore.Http;
using Simple.Services.System;
using Simple.Services.System.QHSEUser.Models;
using Simple.Services.System.QHSEViolationCategory.Models;

namespace Simple.Services;

public class QHSEKeyWorkTypeService
{
    private readonly SimpleDbContext _context;
    public QHSEKeyWorkTypeService(SimpleDbContext context)
    {
        _context = context;
    }
    public async Task<List<QHSEKeyWorkTypeModel>> GetAsync()
    {
        var keyWorkTypes = await _context.Set<QHSESysKeyWorkType>().AsNoTracking().ToListAsync();
        return MapperHelper.Map<List<QHSEKeyWorkTypeModel>>(keyWorkTypes);
    }
    public async Task<List<QHSEKeyWorkTypeModel>> GetAsync(SimpleDbContext context)
    {
        var keyWorkTypes = await context.Set<QHSESysKeyWorkType>().AsNoTracking().ToListAsync();
        return MapperHelper.Map<List<QHSEKeyWorkTypeModel>>(keyWorkTypes);
    }
    public async Task<string> GetCodeByItemAsync(string item)
    {
        var code = await _context.Set<QHSESysKeyWorkType>().AsNoTracking().Where(u=>u.WorkType.Equals(item)).Select(u=>u.WorkTypeCode).FirstOrDefaultAsync();
        return code;
    }
    public async Task<PageResultModel<QHSEKeyWorkTypeModel>> GetPageAsync(QHSEKeyWorkTypePageInputModel input)
    {
        var result = new PageResultModel<QHSEKeyWorkTypeModel>();
        var query = _context.Set<QHSESysKeyWorkType>().AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(input.Code))
        {
            query = query.Where(u => EF.Functions.Like(u.SpecialtyCode, $"{input.Code}%"));

        }
        // 获取总数量
        result.TotalRows = await query.CountAsync();

        // 分页查询
        input.PageSize = result.TotalRows;
        query = query.OrderBy(u => u.OrderNo).Page(input.PageNo, input.PageSize);
        var keyWorkTypes = await query.ToListAsync();
        result.Rows = MapperHelper.Map<List<QHSEKeyWorkTypeModel>>(keyWorkTypes);

        result.SetPage(input);
        result.CountTotalPage();

        return result;
    }
    public async Task<List<string>> GetKeyWorktypesAsync(string workSpeciality)
    {
        var result  =await  _context.Set<QHSESysKeyWorkType>()
            .AsNoTracking()
            .Join(_context.Set<QHSESysKeyWorkSpecialty>(), // Join with Organization table
                        workType => workType.SpecialtyCode,
                        workSpeciality => workSpeciality.SpecialtyCode,
                        (workType, workSpeciality) => new { WorkType = workType, WorkSpeciality = workSpeciality })
            .Where(u => u.WorkSpeciality.Specialty == workSpeciality)
            .Select(joinResult => joinResult.WorkType.WorkType)
            .ToListAsync();

        return result;
    }
}
